package com.nowcoder.controller.intercepor;

import com.nowcoder.annotation.LoginRequired;
import com.nowcoder.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author by lvshh
 * @version 1.0
 * @date 2020/4/25 17:10
 */
@Component
public class LoginRequiredInterceptor implements HandlerInterceptor{

    @Autowired
    private HostHolder hostHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断handler是不是一个方法
        if (handler instanceof HandlerMethod){
            //如果是，则将参数中handler转型为HandlerMethod类型
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            //获得拦截到的method对象
            Method method = handlerMethod.getMethod();
            //是否加了这个注解
            LoginRequired loginRequired = method.getAnnotation(LoginRequired.class);
            //如果方法加了@LoginRequired注解，并且当前没有登录
            if (loginRequired != null && hostHolder.getUser() == null){
                //重定向到登录页面
                response.sendRedirect(request.getContextPath() + "/login");
                return false;
            }
        }
        return true;
    }
}
